import _ from 'lodash';
import HttpClient from '../commons/http-client';
import {UserType} from '../reducers/user';
import {batchUpdateSystemMessage} from '../reducers/system-message-list';
import orderMessageList, {
  batchUpdateOrderMessage,
  readOrderMessage,
  updateOrderMessage,
} from '../reducers/order-message-list';
import {FormStatus, LoadingStatus, updateAppState} from '../reducers/app-state';
import {v4 as uuid} from 'uuid';
import {updateConversation} from '../reducers/conversation';
import {UploadState} from '../components/file-upload';
import orderList from '../reducers/order-list';

export function loadMessages() {
  return async (dispatch, getState) => {
    const {user} = getState();
    dispatch(updateAppState({loading: LoadingStatus.PENDING}));
    try {
      const sysMsgRep = await HttpClient.get(
        '/web/dent/notification?expand=images&no_page=no_page',
      );
      const orderMsgRep = await HttpClient.get(
        `/web/${
          [UserType.dentist, UserType.clinic].includes(user.type)
            ? 'dent'
            : 'vend'
        }/order?fields=id%2Corder_no%2Ccreated%2Cmessages%2Cbuyer%2Cseller%2Cunread%2Cvendor_unread%2Cpatient_name&expand=messages.image%2Cbuyer.avatar%2Cseller.avatar%2C&no_page=no_page`,
      );

      const orders = _.get(orderMsgRep, 'data.data', {});
      const orderUnreadMsgCount = _.sumBy(
        orders,
        [UserType.dentist, UserType.clinic].includes(user.type)
          ? 'unread'
          : 'vendor_unread',
      );
      const unreadSysMsgRep = await HttpClient.get(
        '/web/dent/notification/unread_sys?no_page=no_page',
      );
      dispatch(batchUpdateSystemMessage(sysMsgRep.data.data));
      dispatch(batchUpdateOrderMessage(orders));
      const unreadSysMsg = _.get(unreadSysMsgRep, 'data.data.messages', []);
      // const action = NavigationActions.setParams({params: {unreadSysMsg}});
      // dispatch(action);
      dispatch(
        updateAppState({
          loading: LoadingStatus.DONE,
          unreadSysMsg,
          orderUnreadMsgCount,
        }),
      );
    } catch (e) {
      dispatch(updateAppState({loading: LoadingStatus.ERROR}));
    }
  };
}

export function setConversation(conversation) {
  return dispatch => {
    // dispatch(updateOrder(conversation));
    dispatch(updateConversation(conversation));
    dispatch(readMessage(conversation.id));
  };
}

export function readMessage(id) {
  return async (dispatch, getState) => {
    const {user, orderMessageList} = getState();
    const readRep = await HttpClient.get(
      `/web/${
        user.type === UserType.dentist ? 'dent' : 'vend'
      }/order/${id}/read_all`,
    );
    const orderUnreadMsgCount = _.sumBy(
      orderMessageList,
      [UserType.dentist, UserType.clinic].includes(user.type)
        ? 'unread'
        : 'vendor_unread',
    );
    // console.log(
    //   appState.orderUnreadMsgCount,
    //   currentOrderMsg,
    //   currentOrderMsgCount,
    // );
    dispatch(
      updateAppState({
        orderUnreadMsgCount,
      }),
    );
    dispatch(readOrderMessage(id));
  };
}

export function readSysMessage() {
  return async (dispatch, getState) => {
    const {appState} = getState();
    const readRep = await HttpClient.post('/web/dent/notification/read_sys', {
      id_list: appState.unreadSysMsg.map(msg => msg.id),
    });
    dispatch(updateAppState({unreadSysMsg: []}));
  };
}

export function sendMessage(id, msg) {
  return async (dispatch, getState) => {
    const {user, orderMessageList} = getState();
    const order = orderMessageList[id] || orderList.items[id];
    const message = {
      ...msg,
      uid: uuid(),
      message: msg.content,
      created: new Date(),
      type: user.type === UserType.dentist ? 'buyer' : 'seller',
    };
    order.messages.push(message);
    order.messages.slice();
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const msgRep = await HttpClient.post(
        `/web/${
          user.type === UserType.dentist ? 'dent' : 'vend'
        }/order/${id}/send_message`,
        {message: msg.content, image: msg.imageId},
      );
      // dispatch(updateOrder(order));
      dispatch(updateConversation(order));
      dispatch(updateOrderMessage(order));
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
    }
  };
}

export function appendMessage(id, msg) {
  return async (dispatch, getState) => {
    const {user, orderMessageList} = getState();
    const order = orderMessageList[id];
    const message = {
      ...msg,
      uid: uuid(),
      created: new Date(),
      type: user.type === UserType.dentist ? 'buyer' : 'seller',
    };
    // console.log('append', message);
    order.messages.push(message);
    // console.log('messages', order.messages);
    order.messages.slice();
    // dispatch(updateOrder(order));
    dispatch(updateConversation(order));
    dispatch(updateOrderMessage(order));
  };
}

export function updateMessageImageProgress(id, jobId, percentage) {
  return async (dispatch, getState) => {
    const {orderMessageList} = getState();
    const order = orderMessageList[id];
    order.messages = order.messages.map(msg => {
      if (jobId === msg.jobId) {
        msg.rate = percentage;
        msg.state = UploadState.UPLOADING;
        // console.log('msg', msg);
      }
      return msg;
    });
    // dispatch(updateOrder(order));
    dispatch(updateConversation(order));
    dispatch(updateOrderMessage(order));
  };
}

export function updateMessageImageSuccess(id, jobId, url) {
  return async (dispatch, getState) => {
    const {user, orderMessageList} = getState();
    const order = orderMessageList[id];
    const content = `<img src="${url}" class="message-content-image"/>`;
    // console.log('response', content);
    // order.messages = order.messages.map(msg => {
    //   if (jobId === msg.jobId) {
    //     msg.rate = 100;
    //     msg.state = UploadState.DONE;
    //     msg.message = content;
    //     // console.log('msg', msg);
    //   }
    //   return msg;
    // });
    // console.log('order', order);
    const message = {
      id,
      uid: uuid(),
      created: new Date(),
      type: user.type === UserType.dentist ? 'buyer' : 'seller',
      message: content,
      unread: false,
      rate: 100,
      state: UploadState.DONE,
    };
    order.messages.push(message);
    order.messages.slice();
    const msgRep = await HttpClient.post(
      `/web/${
        user.type === UserType.dentist ? 'dent' : 'vend'
      }/order/${id}/send_message`,
      {message: content},
    );
    // dispatch(updateOrder(order));
    dispatch(updateConversation(order));
    dispatch(updateOrderMessage(order));
  };
}
